const express = require('express');
const router = express.Router();
const db = require('../db');

//注册
//引入utility
const utility = require('utility');

router.post('/reg', (req, res) => {

    //给密码加密
    req.body.password = utility.md5(req.body.password);

    db('insert into user set ?', req.body, (err, result) => {
        err ?
            console.log(err)
            (res.send({
                status: 1,
                message: '注册失败!'
            })) :
            res.send({
                status: 0,
                message: '注册成功!'
            })
    });
});

//登录
//引入jwt
const jwt = require('jsonwebtoken');

router.post('/login', (req, res) => {
    //引入用户名和密码,对密码加密
    let username = req.body.username;
    let password = utility.md5(req.body.password);
    //查询
    db('select * from user where username=? and password=?', [username, password], (err, result) => {

        if (err) {
            console.log(err);
            res.send({
                status: 1,
                message: '登录失败!'
            });
        } else {
            if (result.length == 0) {
                res.send({
                    status: 1,
                    message: '用户名或密码错误!'
                });
            } else {
                //生成token
                let token = 'Bearer ' + jwt.sign({
                    id: result[0].id
                }, 'token', {
                    expiresIn: '5h'
                });
                res.send({
                    status: 0,
                    message: '登录成功!',
                    token: token
                });

            };
        };
    });
});


module.exports = router